<template>
  <div>
    <div style="height: 100%; width: 100%">
      <!-- 调整后的左侧面板结构 -->
      <div class="left-panel-container">
        <!-- <div class="img_left_title">
          <img src="../assets/img/module2/content.png" style="width: 100%" />
          <img src="../assets/img/module2/snailtitleicon.png" @click="toggleAirData" style="
              position: absolute;
              top: 3px;
              left: 15px;
              cursor: pointer;
              pointer-events: auto;
            " />
          <span class="text_left_title">空域对象列表</span>
        </div> -->
        <div class="img_left_title">
          <img src="../assets/img/module2/content.png" style="width: 100%" />
          <img src="../assets/img/module2/snailtitleicon.png" style="position: absolute; top: -10%; left: 6%" />
          <span class="text_left_title">空域运行信息</span>
        </div>

        <!-- 图表和表格使用弹性布局 -->
        <div v-if="tableVisible" class="panel-content">
          <div class="chart-container">
            <div id="airspaceUsageChart" class="chart-item"></div>
            <div id="airspaceAlertChart" class="chart-item"></div>
          </div>
          <button :class="['switch-btn']" @click="showHistoryData">历史容流数据</button>
          <!-- 告警表格 -->
          <div class="alert-table-container">
            <el-table ref="alertTable" :data="alertData" style="width: 100%" class="alert-table"
              @expand-change="handleExpandChange" :expand-row-keys="expands" row-key="id" :row-class-name="getRowClass">
              <el-table-column type="expand">
                <template #default="{ row }">
                  <div class="expand-content" :class="{
                    'warning-expand': row.alertLevel === 4,
                    'danger-expand': row.alertLevel === 5
                  }">
                    <div class="detail-row">
                      <span class="detail-label">处理情况：</span>
                      <span :class="statusClass(row.status)">{{
                        row.status
                      }}</span>
                      <span class="detail-label">告警时段：</span>
                      <span>{{ row.alertTime }}</span>
                    </div>
                    <div class="detail-row">
                      <span class="detail-label">当前流量：</span>
                      <span>{{ row.flow }} 架次/小时</span>
                      <span class="detail-label">空域容量：</span>
                      <span>{{ row.capacity }} 架次/小时</span>
                    </div>
                    <div class="detail-row">
                      <span class="detail-label">预计持续时间：</span>
                      <span>{{ row.duration }}</span>
                    </div>
                    <div class="action-buttons">
                      <el-button size="mini" @click="handleSpecialReport(row)" class="report-btn">
                        特情上报
                      </el-button>
                      <el-button size="mini" type="primary" @click="handleOperationControl(row)" class="control-btn">
                        运行管控
                      </el-button>
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column v-for="col in alertColumns" :key="col.prop" :prop="col.prop" :label="col.label"
                :width="col.width">
                <template #default="{ row }">
                  <span v-if="col.prop === 'alertLevel'" :class="alertLevelClass(row.alertLevel)">
                    {{ getAlertLevel(row.alertLevel) }}
                  </span>
                  <span v-else>{{ row[col.prop] }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <!-- 右侧弹窗内容 -->
      <div class="right-panel-container" v-if="statusDialogVisible">
        <CustomDialog :statusDialogVisible="statusDialogVisible" :selectedObjectName="selectedDetails.name"
          :selectedObjectId="selectedDetails.id" @update:statusDialogVisible="statusDialogVisible = $event">
        </CustomDialog>
      </div>
      <!-- 运行管控弹窗 -->
      <CustomDialogConfirm1 v-if="selectedRow" ref="operationDialog" :visible="operationDialogVisible" :title="'运行管控'"
        :selected-object="selectedRow.name" :selected-start-time="selectedRow.startTime"
        :selected-end-time="selectedRow.endTime" @update:visible="operationDialogVisible = $event" />
    </div>
  </div>
</template>

<script>
import ListTitle from "@/components/ListTitle";
import CustomTable from "@/components/CustomTableModule6Left.vue";
import CustomDialogConfirm1 from "@/components/CustomDialogModule6Confirm1.vue";
import CustomDialog from "@/components/CustomDialogModule6InformationNew.vue";
import Module5AlertResults from '@/views/Module5AlertResults.vue'

import {
  drawCircleArea,
  drawParallelogramArea,
  drawSquareArea,
} from "@/utils/draw2DShapes.js";
import {
  draw3DRectangularPipelineTrackM1_2,
  draw3DRectangularPipelineTrackM1_3,
  draw3DRectangularPipelineTrackM1_4,
  draw3DPolygonalPrismM1,
  drawCylinderAreaM1,
  drawMultipleFixedCylinders,
} from "@/utils/draw3D-module6.js";
import { addDroneModel } from "@/utils/draw3D-module3.js";
import * as echarts from "echarts";
import axios from "axios";

const baseApi =
  process.env.NODE_ENV === "production"
    ? //? process.env.VUE_APP_REMOTE_API
    "/api" // 使用代理路径
    : process.env.VUE_APP_REMOTE_API_MODULE6;
// : "http://192.168.0.135:30027";

const baseWebsocketApi = process.env.VUE_APP_WEBSOCKET;
console.log("basewebsocketapi", baseWebsocketApi);

export default {
  name: "Module6AirspaceManage",
  props: {
    cesiumViewer: {
      type: Object,
      required: true,
    },
  },
  components: {
    CustomTable,
    CustomDialogConfirm1,
    CustomDialog,
    ListTitle,
    Module5AlertResults,
  },
  data() {
    return {
      statusDialogVisible: true, // 状态弹窗显示
      cofirmSubmitDialogVisible: false,
      selectedDetails: {
        startTime: "20240510T08:00:00",
        endTime: "20240510T10:00:00",
      }, // 存储选中的行数据
      selectedSort: "id", // 默认按序号排序
      searchQuery: "", // 搜索关键字
      inverseSort: true, // 排序顺序，默认升序
      tableData: [], // 表格数据从服务器获取
      columns: [
        { prop: "index", label: "#", width: "20%" },
        { prop: "name", label: "空域对象名称", width: "40%" },
        { prop: "airLaneType", label: "空域类型", width: "40%" },
      ],
      tableVisible: true,
      expands: [],
      gisdata: {
        circular: [], // 圆柱体数据
        straight: [], // 航路数据
        polygonal: [], // 多边形柱体数据
        secondCircular: [], // 第二类圆柱体数据
      },
      selectedRow: null, // 记录当前选中的表格行
      operationDialogVisible: false, // 控制弹窗显示
      entityMap: {},
      currentLabelEntity: null, // 记录当前选中的标签实体
      isShowingHanglu: false, // 默认显示航线数据
      droneModels: [],
      wsClosing: true,
      //  positions:[],// 用于存储所有无人机球体的位置
      ws: null,
      // 表格数据
      alertData: [
        {
          index: 1,
          id: "ALERT_001",
          name: "航路1",
          alertLevel: 4,
          status: "待处理",
          alertTime: "09:00 - 11:30",
          flow: 45,
          capacity: 50,
          duration: "150分钟",
          startTime: "2024-05-20T09:00:00",
          endTime: "2024-05-20T11:30:00",
        },
        {
          index: 2,
          id: "ALERT_002",
          name: "航路2",
          alertLevel: 1,
          status: "待处理",
          alertTime: "09:00 - 11:30",
          flow: 20,
          capacity: 50,
          duration: "250分钟",
          startTime: "2024-05-20T09:00:00",
          endTime: "2024-05-20T11:30:00",
        },
        {
          index: 3,
          id: "ALERT_003",
          name: "航路3",
          alertLevel: 5,
          status: "待处理",
          alertTime: "09:00 - 11:30",
          flow: 20,
          capacity: 50,
          duration: "250分钟",
          startTime: "2024-05-20T09:00:00",
          endTime: "2024-05-20T11:30:00",
        },
      ],
      alertColumns: [
        { prop: "index", label: "#", width: "50" },
        { prop: "name", label: "航路名称", width: "150" },
        { prop: "alertLevel", label: "风险等级", width: "100" },
      ],
      airspaceUsageData: [
        { name: "开启", value: 60 },
        { name: "关闭", value: 40 },
      ],
      airspaceAlertData: [
        { name: "安全", value: 70 },
        { name: "预警", value: 20 },
        { name: "告警", value: 10 },
      ],
      selectedEntityName: "", //地图上选中的对象
      module6FinalBaseEntities: [] // 存储 Module6 销毁前绘制的基础航路实体
    };
  },
  async mounted() {
    this.initCharts();
    // 页面加载时获取数据
    const future = this.fetchTableData();
    await future;
    // this.initializeCesium();

    // 组件被挂载时，显示航线
    this.isShowingHanglu = false; // 设置为航线模式
    this.drawgis();
    console.log("组件挂载，显示航线，建立websocket");
    this.S6drawDrone();

    // 绘制完成后进行一次 zoomTo 操作
    this.zoomToEntities();

    // ✅✅✅⭐新增Cesium点击监听逻辑⭐
    const handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    handler.setInputAction(click => {
      const picked = this.viewer.scene.pick(click.position);
      if (Cesium.defined(picked) && picked.id && picked.id.name) {
        const clickedName = picked.id.name;
        console.log("点击了实体：", name);
        // 🎯Vue直接赋值
        this.selectedEntityName = name;
        // console.log("打印一下所有的tableData", this.tableData)

        // // 🎯根据 name 和 airLanetype去 this.tableData 里找
        // const matchedRow = this.tableData.find(row => row.name === clickedName && row.airLaneType === '航路');

        // if (matchedRow) {
        //   this.selectedDetails = {
        //     name: matchedRow.name,
        //     id: matchedRow.id
        //   };
        //   console.log("地图上点击的对象找到了tableData中的实体行", this.selectedDetails);

        //   // 🎯额外：同步展开 alertData 表格
        //   // alertData 是你的表格数据，通常是告警航路的子集
        //   const alertRow = this.alertData.find(row => row.name === matchedRow.name);
        //   if (alertRow) {
        //     this.expands = [alertRow.id];    // ⭐⭐关键：展开行
        //     console.log("同步展开左侧预警表格中的行", alertRow);

        //     // 🎯✅⭐新增：自动滚动到该行
        //     this.$nextTick(() => {
        //       this.scrollToVisibleRow(alertRow);
        //     });
        //   } else {
        //     this.expands = [];               // 如果没找到，清空
        //     console.warn("左侧预警表格中未找到匹配行");
        //   }

        // 查找所有类型的匹配行，不局限于航路  202509修改，可地图选择各类型空域结构赋值给右侧弹窗
        const matchedRow = this.tableData.find(row => row.name === clickedName);

        if (matchedRow) {
          // 更新右侧弹窗数据
          this.selectedDetails = {
            name: matchedRow.name,
            id: matchedRow.id
          };
          console.log("地图上点击的对象找到了tableData中的实体行", this.selectedDetails);

          // 仅当是航路类型时，才处理告警表格展开逻辑
          if (matchedRow.airLaneType === '航路') {
            const alertRow = this.alertData.find(row => row.name === matchedRow.name);
            if (alertRow) {
              this.expands = [alertRow.id];    // 展开行
              console.log("同步展开左侧预警表格中的行", alertRow);

              // 自动滚动到该行
              this.$nextTick(() => {
                this.scrollToVisibleRow(alertRow);
              });
            } else {
              this.expands = [];               // 没找到则清空
            }
          } else {
            // 非航路类型，确保告警表格不展开
            this.expands = [];
          }

          // 确保右侧弹窗显示
          this.statusDialogVisible = true;
        } else {
          console.warn("未找到匹配的tableData行，name为:", name);
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  },
  beforeDestroy() {
    // if (this.viewer) {
    //   this.viewer.destroy();
    //   this.viewer = null;
    // }
    // 组件销毁前，显示航路
    this.isShowingHanglu = true; // 设置为航路模式
    this.drawgis();


    // 核心新增：收集此时 Module6 绘制的所有 Cesium 实体（基础航路+禁飞区等）
    // 从 entityMap 中提取所有实体（entityMap 是 Module6 存储自身实体的容器）
    this.module6FinalBaseEntities = Object.values(this.entityMap)
      .flat() // 因为 entityMap 的 value 可能是数组（如航路实体），需扁平化
      .filter(entity => entity); // 过滤空值，避免异常

    // 3. 传给父组件（CombinedModule）暂存，供 Module1 恢复使用
    this.$emit('store-module6-base-entities', this.module6FinalBaseEntities);
    console.log(`Module6 销毁：已存储 ${this.module6FinalBaseEntities.length} 个基础航路实体`, this.module6FinalBaseEntities);




    // 告诉父组件航路切换执行完毕，可以视情况清除禁飞区
    this.$emit('module6-finished')
    console.log("组件销毁，显示航路，关闭ws");
    if (this.ws) {
      console.log("组件销毁，清除ws连接", this.ws);
      this.wsClosing = true;
      this.ws.onmessage = null;
      this.ws.close();
      this.ws = null;
      this.droneModels = [];
    }

    // 删除弹窗
    this._tooltipDestroyFns?.forEach(fn => fn());
    this._tooltipDestroyFns = [];
  },
  created() {
    // 将传入的 viewer 实例赋值给组件的 data
    this.viewer = this.cesiumViewer;
    console.log("Module6子组件获得的this.viewer", this.viewer);
  },
  methods: {
    showHistoryData() {
      this.$router.push("/alert-results");
    },
    getRowClass({ row }) {
      if (row.alertLevel === 4) {
        return "warning-row";
      } else if (row.alertLevel === 5) {
        return "danger-row";
      }
      return "";
    },
    setEntityOpacity(entity, alpha) {
      if (!entity || !entity.corridor) return;

      // 判断材质类型是否为 PolylineGlowMaterialProperty
      const material = entity.corridor.material;
      if (material instanceof Cesium.PolylineGlowMaterialProperty) {
        // 获取当前颜色
        const currentColor = material.color?.getValue(Cesium.JulianDate.now());

        if (currentColor) {
          const newColor = Cesium.Color.fromAlpha(currentColor, alpha);
          material.color.setValue(newColor); // ✅ 动态更新材质颜色的透明度
        }
      } else {
        console.warn('实体不是 PolylineGlow 材质，不能变透明');
      }
    },
    highlightEntity(entity, alpha = 1) {
      const material = entity?.corridor?.material;
      const outlineColor = entity?.corridor?.outlineColor;

      // 修改走廊的主材质透明度
      if (material instanceof Cesium.PolylineGlowMaterialProperty) {
        const color = material.color?.getValue(Cesium.JulianDate.now());
        if (color) {
          material.color.setValue(Cesium.Color.fromAlpha(color, alpha));
        }
      }

      // 修改轮廓颜色
      if (outlineColor instanceof Cesium.ConstantProperty) {
        const color = outlineColor.getValue(Cesium.JulianDate.now());
        if (color) {
          entity.corridor.outlineColor = Cesium.Color.fromAlpha(color, alpha);
        }
      }

      // 修改标签可见性
      if (entity.label) {
        if (alpha === 1) {
          entity.label.distanceDisplayCondition = null; // 不限制显示
        } else {
          entity.label.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(0.0, 4000.0); // 恢复限制
        }
      }
    },
    handleExpandChange(row, expandedRows) {
      if (expandedRows.length > 0) {
        this.expands = [row.id];
        this.scrollToVisibleRow(row);
        // this.flyToAlertEntity(row); // 地图聚焦
        // 🔍 找到实体
        const entity = this.findEntityByName(row.name);
        if (entity) {
          // // ✅ 取消上一个高亮
          // if (this.currentFocusedEntity) {
          //   this.highlightEntity(this.currentFocusedEntity, 0.5);
          // }
          // // ✅ 设置当前高亮
          // this.highlightEntity(entity, 1);
          this.currentFocusedEntity = entity;

          this.viewer.flyTo(entity, {
            duration: 2,
            offset: {
              heading: Cesium.Math.toRadians(0),
              pitch: Cesium.Math.toRadians(-30),
              range: 3000,
            }
          });

          console.log("选中的row的所有信息", row)

          // 🎯根据 name 和 airLanetype去 this.tableData 里找
          const matchedRow = this.tableData.find(originRow => originRow.name === row.name && originRow.airLaneType === '航路');

          // ✅ 设置右侧弹窗数据
          if (matchedRow) {
            this.selectedDetails = {
              name: matchedRow.name,
              id: matchedRow.id
            };
            console.log("左侧弹窗展开的对象找到了tableData中的实体行", this.selectedDetails);
          } else {
            console.warn("未找到匹配的tableData行，name为:", name);
          }

          this.statusDialogVisible = true;
        }
      } else {
        this.expands = [];

        // // 如果之前有聚焦实体，恢复透明度
        // if (this.currentFocusedEntity) {
        //   this.setEntityOpacity(this.currentFocusedEntity, 0.5);
        //   this.currentFocusedEntity = null;
        // }
        // ✅ 收起时恢复透明度
        if (this.currentFocusedEntity) {
          this.highlightEntity(this.currentFocusedEntity, 0.5);
          this.currentFocusedEntity = null;
        }
      }
    },
    findEntityByName(name) {
      console.log("要找的实体的name", name)
      return Object.values(this.entityMap)
        .flat()
        .find(ent => {
          const val = typeof ent.name?.getValue === 'function'
            ? ent.name.getValue(Cesium.JulianDate.now())
            : ent.name;
          return val === name;
        });
    },
    scrollToVisibleRow(row) {
      if (row) {
        const table = this.$refs.alertTable;
        const bodyWrapper = table.$el.querySelector(".el-table__body-wrapper");

        this.$nextTick(() => {
          // ⭐直接找data-rowkey标记的行
          const rowElement = bodyWrapper.querySelector(`tr[data-rowkey="${row.id}"]`);

          if (rowElement) {
            const rowRect = rowElement.getBoundingClientRect();
            const bodyWrapperRect = bodyWrapper.getBoundingClientRect();

            const isRowFullyVisible =
              rowRect.top >= bodyWrapperRect.top &&
              rowRect.bottom <= bodyWrapperRect.bottom;

            if (!isRowFullyVisible) {
              // 滚动使当前行位于可视区顶部
              const scrollTop = bodyWrapper.scrollTop;
              const targetScrollTop = scrollTop + rowRect.top - bodyWrapperRect.top;
              bodyWrapper.scrollTop = targetScrollTop;
            }
          } else {
            console.warn(`❗scrollToVisibleRow未找到data-rowkey=${row.id}的行`);
          }
        });
      }
    }
    ,
    flyToAlertEntity(row) {
      const alertName = row.name;

      const entity = Object.values(this.entityMap).flat().find(ent => {
        const nameProp = ent.properties?.name;
        const name = typeof nameProp?.getValue === 'function'
          ? nameProp.getValue(Cesium.JulianDate.now())
          : nameProp;
        return name === alertName;
      });

      if (entity) {
        // 保存当前聚焦实体
        this.currentFocusedEntity = entity;

        // 变成不透明
        this.setEntityOpacity(entity, 1.0);

        // 地图飞过去
        this.viewer.flyTo(entity, {
          duration: 2,
          offset: {
            heading: Cesium.Math.toRadians(0),
            pitch: Cesium.Math.toRadians(-30),
            range: 3000,
          }
        });
      } else {
        console.warn('❗未找到匹配的航线实体:', alertName);
      }
    },
    getAlertLevel(level) {
      const levels = {
        1: "安全",
        2: "安全",
        3: "安全",
        4: "预警",
        5: "告警",
      };
      return levels[level] || "未知";
    },
    // 设置状态样式
    statusClass(status) {
      return {
        "status-processing": status === "处理中",
        "status-resolved": status === "已处理",
        "status-pending": status === "待处理",
      };
    },
    // 设置风险等级样式
    alertLevelClass(level) {
      return {
        "alert-level-4": level === 4,
        "alert-level-5": level === 5,
      };
    },
    // 处理运行管控
    handleOperationControl(row) {
      // this.selectedRow = row;
      // this.operationDialogVisible = true;

      // 1. 开启全屏 loading
      const loading = this.$loading({
        lock: true,
        text: '智能算法正在运算最佳运行管控参数...',
        background: 'rgba(0, 0, 0, 0.7)',
      });

      // 2. 模拟异步操作或等待数据加载（可替换为真实请求）
      setTimeout(() => {
        // 设置所选数据
        this.selectedRow = row;
        this.operationDialogVisible = true;

        // 3. 关闭 loading
        loading.close();
      }, 1000); // 你可以根据实际加载时间来调整

    },

    // 处理特情上报
    handleSpecialReport(row) {
      this.$emit("special-report", row);
    },
    // 初始化饼图
    async initCharts() {
      this.initUsageChart();
      this.initAlertChart();
    },

    async initUsageChart() {
      const chart = echarts.init(document.getElementById("airspaceUsageChart"));
      chart.setOption({
        title: {
          text: "空域使用状态",
          left: "center",
          textStyle: { color: "#fff", fontSize: 14 },
        },
        tooltip: { trigger: "item" },
        legend: {
          bottom: "5%",
          left: "center",
          itemWidth: 10,
          itemHeight: 10,
          textStyle: { color: "#fff" },
        },
        series: [
          {
            type: "pie",
            radius: ["30%", "50%"],
            data: this.airspaceUsageData,
            label: {
              show: false,
              position: "center",
            },
          },
        ],
      });
    },

    async initAlertChart() {
      const chart = echarts.init(document.getElementById("airspaceAlertChart"));
      chart.setOption({
        title: {
          text: "容流告警状态",
          left: "center",
          textStyle: { color: "#fff", fontSize: 14 },
        },
        tooltip: { trigger: "item" },
        legend: {
          bottom: "5%",
          left: "center",

          itemWidth: 10,
          itemHeight: 10,
          textStyle: { color: "#fff" },
        },
        series: [
          {
            type: "pie",
            radius: ["30%", "50%"],
            data: this.airspaceAlertData,
            label: {
              show: false,
              position: "center",
            },
          },
        ],
        color: ["deepskyblue", "orange", "lightcoral"],
      });
    },

    getAlertLevel(level) {
      return ["安全", "安全", "安全", "预警", "告警"][level - 1];
    },
    async drawgis() {
      try {
        this.viewer.entities.removeAll();
        // 传给父组件进行标注的特殊区域
        const redPolygonEntities = [];
        // this.refreshGISdata();
        const { circular, polygonal, straight, secondCircular } = this.gisdata;
        const entitiesToFlyTo = [];
        console.log("更新 GIS 绘制数据", this.gisdata);

        // 绘制圆柱体
        if (circular && circular.length > 0) {
          circular.forEach((cylinder, index) => {
            let entity;

            // 判断 activeidentityid 并调用不同的绘制函数
            if (cylinder.activeidentityid === "main_qijiang") {
              // 如果 activeidentityid 为 "main_qijiang"，调用 drawMultipleFixedCylinders
              entity = drawMultipleFixedCylinders(
                this.viewer,
                cylinder.longitude,
                cylinder.latitude,
                cylinder.minAltitude,
                cylinder.maxAltitude,
                cylinder.radius,
                cylinder.color,
                0.5,
                cylinder.text
              );
            } else if (cylinder.activeidentityid === "main_1") {
              // 如果 activeidentityid 为 "main_1"，调用原来的 drawCylinderAreaM1
              entity = drawCylinderAreaM1(
                this.viewer,
                cylinder.longitude,
                cylinder.latitude,
                cylinder.minAltitude,
                cylinder.maxAltitude,
                cylinder.radius,
                cylinder.color,
                0.5,
                cylinder.text
              );
            }
            if (entity) {
              entity.properties = new Cesium.PropertyBag({
                index: cylinder.index,
                activeIndex: cylinder.activeidentityid,
                type: "circular",
              });
              this.addEntity(cylinder.activeidentityid, cylinder.index, entity);
              entitiesToFlyTo.push(entity);
            }
          });
        }

        // 绘制第二类圆柱体
        if (secondCircular && secondCircular.length > 0) {
          secondCircular.forEach((cylinder, index) => {
            const entity = drawCylinderAreaM1(
              this.viewer,
              cylinder.longitude,
              cylinder.latitude,
              cylinder.minAltitude,
              cylinder.maxAltitude,
              cylinder.radius,
              cylinder.color,
              0.5,
              cylinder.text
            );
            if (entity) {
              entity.properties = new Cesium.PropertyBag({
                index: cylinder.index,
                activeIndex: cylinder.activeidentityid,
                type: "circular",
              });
              this.addEntity(cylinder.activeidentityid, cylinder.index, entity);
              entitiesToFlyTo.push(entity);
            }
          });
        }

        // 绘制多边形柱体
        if (polygonal && polygonal.length > 0) {
          polygonal.forEach((polygon, index) => {
            // console.log("zhubeide多边体数据了", polygon)
            if (
              polygon.coordinates &&
              Array.isArray(polygon.coordinates) &&
              polygon.coordinates.length > 0
            ) {
              let opacity = polygon.color === "RED" ? 0.3 : 0.5;

              // 检查 text 是否是 "珠海机场"
              if (polygon.text !== "珠海机场") {
                opacity = 0.05; // 如果不是珠海机场，则降低透明度，最低为 0
              }

              const entity = draw3DPolygonalPrismM1(
                this.viewer,
                polygon.coordinates
                  .map((coord) => [coord.longitude, coord.latitude])
                  .flat(),
                polygon.minAltitude,
                polygon.maxAltitude,
                polygon.color,
                // 0.5,
                opacity,
                polygon.text
              );
              if (entity) {
                entity.properties = new Cesium.PropertyBag({
                  index: polygon.index,
                  activeIndex: polygon.activeidentityid,
                  type: "polygonal",
                });
                this.addEntity(polygon.activeidentityid, polygon.index, entity);
                entitiesToFlyTo.push(entity);

                // 🚨 如果是红色柱体，加入集合
                if (polygon.color === "RED") {
                  redPolygonEntities.push(entity);
                }
              }
            } else {
              console.log(`Polygon ${index} 的 coordinates 数据为空或未定义`);
            }
          });

          redPolygonEntities.forEach(ent => ent.show = false); // 初始不显示
          // 🚀 将红色柱体通知给父组件
          this.$emit("update-red-polygons", redPolygonEntities);
        }

        // // 绘制长方体管道
        // if (straight && straight.length > 0) {
        //   console.log("绘制长方体管道数据", straight);
        //   straight.forEach((pipeline, index) => {
        //     // const coordinates = pipeline.coordinates.map(coord => [coord.longitude, coord.latitude, coord.altitude]).flat();
        //     const coordinates = pipeline.coordinates.map(coord => [coord.longitude, coord.latitude, pipeline.maxAltitude]).flat();
        //     // const sizes = new Array(coordinates.length / 3 - 1).fill([100, 50]);
        //     const sizes = new Array(coordinates.length / 3 - 1).fill([100, pipeline.maxAltitude - pipeline.minAltitude]);

        //     if (sizes.length === coordinates.length / 3 - 1) {
        //       const entities = draw3DRectangularPipelineTrackM1_2(
        //         this.viewer,
        //         coordinates,
        //         sizes,
        //         0.5,
        //         pipeline.color,
        //         pipeline.text
        //       );
        //       if (entities) {
        //         entities.forEach((entity, num) => {
        //           entity.properties = new Cesium.PropertyBag({
        //             index: pipeline.index,
        //             activeIndex: pipeline.activeidentityid,
        //             type: 'straight',
        //           });
        //           entitiesToFlyTo.push(entity);
        //         });
        //         this.addEntity(pipeline.activeidentityid, pipeline.index, entities);
        //       }
        //     } else {
        //       console.error('Sizes array length does not match coordinates array length minus one');
        //     }
        //   });
        // }
        // 绘制长方体管道数据（航线和航路）
        if (straight && straight.length > 0) {
          // 航线的mock表格展示数据
          const generatedAlertData = [];
          let id = 1
          console.log("绘制长方体管道数据", straight);
          // straight.forEach((pipeline, idx) => {
          //   // 判断是否绘制该管道数据
          //   const isHangXian = pipeline.color === "DEEPSKYBLUE";
          //   const isZadao = pipeline.color === "DARKCYAN"; // 始终要绘制的匝道

          //   if (
          //     isZadao ||
          //     (isHangXian && !this.isShowingHanglu) ||
          //     (!isHangXian && this.isShowingHanglu)
          //   ) {
          //     const alertLevel = Math.ceil(Math.random() * 5);
          //     let alertFlow = 0;

          //     if (alertLevel === 1) {
          //       alertFlow = Math.floor(Math.random() * 11); // 0 ~ 10
          //     } else if (alertLevel === 2) {
          //       alertFlow = Math.floor(Math.random() * 11) + 10; // 10 ~ 20
          //     } else if (alertLevel === 3) {
          //       alertFlow = Math.floor(Math.random() * 11) + 20; // 20 ~ 30
          //     } else if (alertLevel === 4) {
          //       alertFlow = Math.floor(Math.random() * 11) + 30; // 30 ~ 40
          //     } else if (alertLevel === 5) {
          //       alertFlow = Math.floor(Math.random() * 61) + 40; // 40 ~ 100
          //     }


          //     // 默认颜色
          //     let alertColor = pipeline.color;
          //     // 只有是“航线”时，才根据告警等级改变颜色
          //     if (isHangXian || !isHangXian) {
          //       if (alertLevel === 4) {
          //         alertColor = 'orange'; // 橙色
          //       } else if (alertLevel === 5) {
          //         alertColor = 'lightcoral'; // 淡红色
          //       }
          //     }
          //     // 👇 在这里记录模拟表格数据
          //     generatedAlertData.push({
          //       index: id,
          //       id: `ALERT_${String(idx + 1).padStart(3, '0')}`,
          //       name: pipeline.text,
          //       alertLevel: alertLevel,
          //       status: "待处理",
          //       alertTime: "09:00 - 11:30",
          //       flow: Math.floor(Math.random() * 40 + 10),
          //       capacity: 50,
          //       duration: `${90 + Math.floor(Math.random() * 120)}分钟`,
          //       startTime: "2024-05-20T09:00:00",
          //       endTime: "2024-05-20T11:30:00",
          //     });
          //     id += 1
          //     // 设置坐标和尺寸
          //     const coordinates = pipeline.coordinates
          //       .map((coord) => [
          //         coord.longitude,
          //         coord.latitude,
          //         pipeline.maxAltitude,
          //       ])
          //       .flat();
          //     const sizes = new Array(coordinates.length / 3 - 1).fill([
          //       100,
          //       pipeline.maxAltitude - pipeline.minAltitude,
          //     ]);

          //     // 绘制长方体管道
          //     if (sizes.length === coordinates.length / 3 - 1) {
          //       // const entities = draw3DRectangularPipelineTrackM1_2(
          //       //   this.viewer,
          //       //   coordinates,
          //       //   sizes,
          //       //   0.5,
          //       //   // pipeline.color,
          //       //   alertColor,
          //       //   pipeline.text
          //       // );
          //       const entities = isHangXian
          //         ? draw3DRectangularPipelineTrackM1_3(
          //           this.viewer,
          //           coordinates,
          //           sizes,
          //           0.5,
          //           alertColor,
          //           pipeline.text,
          //           [], // pointNames
          //           Cesium.CornerType.ROUNDED, // cornerType
          //           alertLevel,  // ✅ 告警等级
          //           alertFlow    // ✅ 当前流量
          //         )
          //         : draw3DRectangularPipelineTrackM1_3(
          //           this.viewer,
          //           coordinates,
          //           sizes,
          //           0.5,
          //           alertColor,
          //           pipeline.text,
          //           [], // pointNames
          //           Cesium.CornerType.ROUNDED, // cornerType
          //           alertLevel,  // ✅ 告警等级
          //           alertFlow    // ✅ 当前流量
          //         );
          //       if (entities) {
          //         entities.forEach((entity) => {
          //           entity.properties = new Cesium.PropertyBag({
          //             index: pipeline.index,
          //             activeIndex: pipeline.activeidentityid,
          //             type: isHangXian ? "airLane" : "straight", // 设置类型
          //             name: pipeline.text, // ✅ 在 properties 里加 name 字段
          //           });
          //           entitiesToFlyTo.push(entity);
          //         });
          //         this.addEntity(
          //           pipeline.activeidentityid,
          //           pipeline.index,
          //           entities
          //         );
          //       }
          //     } else {
          //       console.error(
          //         "Sizes array length does not match coordinates array length minus one"
          //       );
          //     }
          //   }

          //   // 设置到 data 里用于表格展示
          //   // this.alertData = generatedAlertData;
          //   this.alertData = generatedAlertData
          //     .filter(item => item.alertLevel >= 4)
          //     .map((item, idx) => ({
          //       ...item,
          //       index: idx + 1, // 重新设置为连续编号
          //     }));
          // });
          // 检查是否存在 alertLevel >= 4 的告警项

          // 统计当前生成的预警航路和告警航路数量
          let warningCount = 0;
          let alertCount = 0;

          straight.forEach((pipeline, idx) => {
            const isHangXian = pipeline.color === "DEEPSKYBLUE";
            const isZadao = pipeline.color === "DARKCYAN";

            if (this.isShowingHanglu) {
              // 航路模式：只绘制航路
              if (!isHangXian) {
                const coordinates = pipeline.coordinates.map(coord => [
                  coord.longitude,
                  coord.latitude,
                  pipeline.maxAltitude
                ]).flat();

                const sizes = new Array(coordinates.length / 3 - 1).fill([
                  100,
                  pipeline.maxAltitude - pipeline.minAltitude
                ]);

                if (sizes.length === coordinates.length / 3 - 1) {
                  const entities = draw3DRectangularPipelineTrackM1_2(
                    this.viewer,
                    coordinates,
                    sizes,
                    0.5,
                    pipeline.color,
                    pipeline.text
                  );

                  if (entities) {
                    entities.forEach(entity => {
                      entity.properties = new Cesium.PropertyBag({
                        index: pipeline.index,
                        activeIndex: pipeline.activeidentityid,
                        type: "straight",
                        name: pipeline.text
                      });
                      entitiesToFlyTo.push(entity);
                    });
                    this.addEntity(
                      pipeline.activeidentityid,
                      pipeline.index,
                      entities
                    );
                  }
                }
              }
            } else {
              // 航线+告警航路模式
              if (isHangXian) {
                // 绘制航线
                const alertLevel = Math.ceil(Math.random() * 5);
                let alertFlow = 0;
                if (alertLevel === 1) alertFlow = Math.floor(Math.random() * 11);
                else if (alertLevel === 2) alertFlow = Math.floor(Math.random() * 11) + 10;
                else if (alertLevel === 3) alertFlow = Math.floor(Math.random() * 11) + 20;
                else if (alertLevel === 4) alertFlow = Math.floor(Math.random() * 11) + 30;
                else if (alertLevel === 5) alertFlow = Math.floor(Math.random() * 61) + 40;

                // 航线没有告警颜色，统一颜色
                let alertColor = pipeline.color;

                const coordinates = pipeline.coordinates.map(coord => [
                  coord.longitude,
                  coord.latitude,
                  pipeline.maxAltitude
                ]).flat();

                const sizes = new Array(coordinates.length / 3 - 1).fill([
                  100,
                  pipeline.maxAltitude - pipeline.minAltitude
                ]);

                if (sizes.length === coordinates.length / 3 - 1) {
                  const entities = draw3DRectangularPipelineTrackM1_3(
                    this.viewer,
                    coordinates,
                    sizes,
                    0.5,
                    alertColor,
                    pipeline.text,
                    [],
                    Cesium.CornerType.ROUNDED,
                    // alertLevel,
                    // 航线没有告警等级
                    1,
                    alertFlow
                  );

                  if (entities) {
                    entities.forEach(entity => {
                      entity.properties = new Cesium.PropertyBag({
                        index: pipeline.index,
                        activeIndex: pipeline.activeidentityid,
                        type: "airLane",
                        name: pipeline.text
                      });
                      entitiesToFlyTo.push(entity);
                    });
                    this.addEntity(
                      pipeline.activeidentityid,
                      pipeline.index,
                      entities
                    );
                  }
                }
              } else {
                // 航路：只绘制告警航路
                // const alertLevel = Math.ceil(Math.random() * 5);
                if (true) {
                  // let alertFlow = 0;
                  // if (alertLevel === 1) alertFlow = Math.floor(Math.random() * 11);
                  // else if (alertLevel === 2) alertFlow = Math.floor(Math.random() * 11) + 10;
                  // else if (alertLevel === 3) alertFlow = Math.floor(Math.random() * 11) + 20;
                  // else if (alertLevel === 4) alertFlow = Math.floor(Math.random() * 11) + 30;
                  // else if (alertLevel === 5) alertFlow = Math.floor(Math.random() * 61) + 40;
                  // Step 1: 随机一个原始等级
                  let alertLevel = Math.ceil(Math.random() * 5);
                  let originalLevel = alertLevel;

                  // Step 2: 检查是否超量，若超，则降级为安全等级（1~3）
                  if ((alertLevel === 4 && warningCount >= 5) || (alertLevel === 5 && alertCount >= 2)) {
                    alertLevel = Math.floor(Math.random() * 3) + 1; // 强制变为安全等级
                  }

                  // Step 3: 按等级生成对应流量
                  let alertFlow = 0;
                  if (alertLevel === 1) alertFlow = Math.floor(Math.random() * 2); // 0–1
                  else if (alertLevel === 2) alertFlow = Math.floor(Math.random() * 2) + 2; // 2–3
                  else if (alertLevel === 3) alertFlow = 4;
                  else if (alertLevel === 4) alertFlow = Math.floor(Math.random() * 2) + 5; // 5–6
                  else if (alertLevel === 5) alertFlow = Math.floor(Math.random() * 2) + 7; // 7–8

                  // Step 4: 设置颜色
                  let alertColor = pipeline.color;
                  if (alertLevel === 4) alertColor = 'orange';
                  else if (alertLevel === 5) alertColor = 'lightcoral';

                  // if (alertLevel >= 4) {
                  // Step 5: 记录真正的预警/告警数据（没有被降级的才记录）
                  if (alertLevel === originalLevel && alertLevel >= 4) {
                    if (alertLevel === 4) warningCount++;
                    else if (alertLevel === 5) alertCount++;

                    // ✅ 只记录告警航路
                    generatedAlertData.push({
                      index: id,
                      id: `ALERT_${String(idx + 1).padStart(3, '0')}`,
                      name: pipeline.text,
                      alertLevel: alertLevel,
                      status: "待处理",
                      alertTime: "09:00 - 11:30",
                      flow: alertFlow,
                      capacity: 8,
                      duration: `${90 + Math.floor(Math.random() * 120)}分钟`,
                      startTime: "2024-05-20T09:00:00",
                      endTime: "2024-05-20T11:30:00",
                    });
                    id += 1;
                  }

                  const coordinates = pipeline.coordinates.map(coord => [
                    coord.longitude,
                    coord.latitude,
                    pipeline.maxAltitude
                  ]).flat();

                  const sizes = new Array(coordinates.length / 3 - 1).fill([
                    100,
                    pipeline.maxAltitude - pipeline.minAltitude
                  ]);

                  if (sizes.length === coordinates.length / 3 - 1) {
                    // const entities = draw3DRectangularPipelineTrackM1_4(
                    //   this.viewer,
                    //   coordinates,
                    //   sizes,
                    //   0.5,
                    //   alertColor,
                    //   pipeline.text,
                    //   [],
                    //   Cesium.CornerType.ROUNDED,
                    //   alertLevel,
                    //   alertFlow
                    // );

                    // if (entities) {
                    //   entities.forEach(entity => {
                    //     entity.properties = new Cesium.PropertyBag({
                    //       index: pipeline.index,
                    //       activeIndex: pipeline.activeidentityid,
                    //       type: "straight",
                    //       name: pipeline.text
                    //     });
                    //     entitiesToFlyTo.push(entity);
                    //   });
                    //   this.addEntity(
                    //     pipeline.activeidentityid,
                    //     pipeline.index,
                    //     entities
                    //   );
                    // }
                    const result = draw3DRectangularPipelineTrackM1_4(
                      this.viewer,
                      coordinates,
                      sizes,
                      0.5,
                      alertColor,
                      pipeline.text,
                      [],
                      Cesium.CornerType.ROUNDED,
                      alertLevel,
                      alertFlow
                    );

                    if (result?.entities) {
                      result.entities.forEach(entity => {
                        entity.properties = new Cesium.PropertyBag({
                          index: pipeline.index,
                          activeIndex: pipeline.activeidentityid,
                          type: "straight",
                          name: pipeline.text
                        });
                        entitiesToFlyTo.push(entity);
                      });
                      this.addEntity(
                        pipeline.activeidentityid,
                        pipeline.index,
                        result.entities
                      );
                    }

                    // ✅ 保存 destroy 方法引用，供页面跳转时关闭 tooltip
                    this._tooltipDestroyFns ??= [];
                    if (typeof result?.destroy === 'function') {
                      this._tooltipDestroyFns.push(result.destroy);
                    }
                  }
                }
              }
            }
          });

          // const hasCriticalAlert = generatedAlertData.some(item => item.alertLevel >= 4);

          // if (hasCriticalAlert) {
          //   this.$message({
          //     message: '出现异常情况，请及时处理！',
          //     type: 'warning'
          //   });
          // }
          // ✅ 更新表格数据
          this.alertData = generatedAlertData.map((item, idx) => ({
            ...item,
            index: idx + 1
          }));

          // ✅ 弹出提示
          if (generatedAlertData.length > 0) {
            this.$message({
              message: '出现异常情况，请及时处理！',
              type: 'warning'
            });
          }
        }

        // 调整视角
        if (entitiesToFlyTo.length > 0) {
          // this.viewer.flyTo(entitiesToFlyTo, {
          //   duration: 2,
          //   offset: {
          //     heading: Cesium.Math.toRadians(0),
          //     pitch: Cesium.Math.toRadians(-30),
          //   },
          // });
          this.viewer.flyTo(this.viewer.entities, {
            duration: 1, // 飞行动画持续时间，可自行调整
            offset: new Cesium.HeadingPitchRange(
              Cesium.Math.toRadians(150), // 朝向角度
              Cesium.Math.toRadians(-40), // 俯仰角度
              10000 // 距离（可以调整至适合的视距）
            ),
          });
        }
        console.log("所有实体名：", this.viewer.entities.values.map(e => e.name));
        console.log("entityMap", this.entityMap);
      } catch (error) {
        console.error("更新 GIS 数据时出错:", error);
      }
    },
    // 添加实体函数
    addEntity(id1, id2, entity) {
      const key = `${id1}-${id2}`; // 组合 id1 和 id2 作为唯一键
      this.entityMap[key] = entity; // 存储实体
    },
    // 获取实体函数
    getEntity(id1, id2) {
      const key = `${id1}-${id2}`; // 组合 id1 和 id2 生成键
      return this.entityMap[key]; // 获取对应实体
    },
    sortTable() {
      // 重新获取排序后的数据
      this.fetchTableData();
    },
    sortInverse() {
      this.inverseSort = !this.inverseSort;
      this.fetchTableData();
    },

    filterTable() {
      // 触发搜索过滤，重新获取数据
      this.fetchTableData();
    },
    refreshTable() {
      // 刷新表格数据，重置搜索和排序
      this.selectedSort = "id";
      this.searchQuery = "";
      this.fetchTableData();
    },
    handleViewDetails(row) {
      this.selectedDetails = row; // 将点击的行数据保存
      console.log("左弹窗选中的行的数据", this.selectedDetails);
      this.statusDialogVisible = true; // 显示弹窗

      // 使用对象的 `id` 和 `type` 调用透明度更改和视角聚焦
      this.entityViewChange(row.mainType, row.sequence, row.shapeCategory);
    },
    entityViewChange(id1, id2, type) {
      const entity = this.getEntity(id1, id2);
      console.log("选中即将切换视角的entity", entity);

      // 获取当前视角的参数
      const currentView = this.viewer.camera;
      const currentHeading = currentView.heading;
      const currentPitch = currentView.pitch;
      const currentRoll = currentView.roll;

      // 计算飞行时间，根据实体的高度调整
      let duration = 5; // 默认飞行时间为5秒

      // 实体包含 minAltitude 和 maxAltitude 属性
      const altitudeDifference =
        entity.maxAltitude && entity.minAltitude
          ? entity.maxAltitude - entity.minAltitude
          : 100; // 若未提供高度信息，默认设置为100米

      // 计算最小视角距离，避免视角太近
      const minRange = Math.max(altitudeDifference * 10, 1000); // 根据高度调整视角距离，最小距离为500米

      if (Cesium.defined(entity)) {
        // 临时飞行到实体位置，获取默认的 range 值
        this.viewer
          .flyTo(entity, {
            duration: duration,
            offset: {
              heading: currentHeading,
              pitch: Cesium.Math.toRadians(-30),
              roll: currentRoll,
              range: undefined, // 不设置 range 以获取默认的飞行距离
            },
          })
          .then(() => {
            // 获取默认的 range 值
            const defaultRange = this.viewer.camera.positionCartographic.height;

            // 选取较大值作为最终的 range
            const finalRange = Math.max(minRange, defaultRange);

            // 重新飞行到实体，使用最终的 range 值
            this.viewer.flyTo(entity, {
              duration: 2,
              offset: {
                heading: currentHeading,
                pitch: Cesium.Math.toRadians(-30),
                roll: currentRoll,
                range: finalRange, // 使用最终的 range
              },
            });

            // 调用颜色和透明度更改方法
            this.entityChangeColor(entity, type);
          });
        // 调用颜色和透明度更改方法
        // this.entityChangeColor(entity, type);
      }
    },
    entityChangeColor(entityAgent, type) {
      // 上一个点击的实体恢复颜色
      if (this.currentLabelEntity) {
        this.currentColor.alpha = 0.2;
        if (this.currentEntityType == "straight") {
          this.currentLabelEntity.forEach((entity) => {
            entity.material.color = this.currentColor;
            console.log("此时的entity", entity);
            // 恢复距离限制
            if (entity.label) {
              entity.label.distanceDisplayCondition =
                new Cesium.DistanceDisplayCondition(0.0, 4000.0);
            }
          });
        } else {
          this.currentLabelEntity.material.color = this.currentColor;
          console.log("此时的this.currentLabelEntity", this.currentLabelEntity);
          if (this.currentLabelEntity.label) {
            this.currentLabelEntity.label.distanceDisplayCondition =
              new Cesium.DistanceDisplayCondition(0.0, 4000.0);
          }
        }
      }
      //更新当前实体的种类
      this.currentEntityType = type;
      console.log("entityAgententityAgent", entityAgent);
      console.log("type", type);
      // 对当前点击的实体进行颜色变化
      if (type === "circular") {
        this.currentLabelEntity = entityAgent.cylinder;
      } else if (type === "polygonal") {
        this.currentLabelEntity = entityAgent.polygon;
        console.log("entityAgent.polygon", entityAgent.polygon);
      } else if (type === "straight") {
        this.currentLabelEntity = entityAgent.map((entity) => entity.corridor);
      }
      if (this.currentEntityType == "straight") {
        this.currentColor = this.currentLabelEntity[0].material.color
          .getValue(Cesium.JulianDate.now())
          .clone();
        this.currentColor.alpha = 1;
        this.currentLabelEntity.forEach((entity) => {
          entity.material.color = this.currentColor;
          // 移除距离限制
          if (entity.label) {
            entity.label.distanceDisplayCondition = null;
          }
        });
      } else {
        this.currentColor = this.currentLabelEntity.material.color
          .getValue(Cesium.JulianDate.now())
          .clone();
        this.currentColor.alpha = 1;
        this.currentLabelEntity.material.color = this.currentColor;
        if (this.currentLabelEntity.label) {
          this.currentLabelEntity.label.distanceDisplayCondition = null;
        }
      }
      console.log("完成实体的变色");
    },
    zoomToShape(lon, lat, altitude) {
      const camera = this.viewer.camera;

      // 设置飞行到目标位置的参数
      const destination = Cesium.Cartesian3.fromDegrees(
        lon,
        lat - 0.03,
        altitude + 1000
      ); // 飞行到该形状
      const heading = Cesium.Math.toRadians(0); // 指向 0 度（北方）
      const pitch = Cesium.Math.toRadians(-30); // 设置俯视角度为 -30 度（相当于抬高一些）
      const roll = Cesium.Math.toRadians(0); // 无滚转

      // 使用 flyTo 实现平滑过渡，调整视角
      camera.flyTo({
        destination: destination,
        orientation: {
          heading: heading,
          pitch: pitch,
          roll: roll,
        },
        duration: 2.0, // 飞行时间（单位：秒）
        offset: {
          heading: heading,
          pitch: pitch,
        },
      });
    },
    hoverLeave() {
      // this.statusDialogVisible = false;
    },

    submitVisibleChange() {
      this.cofirmSubmitDialogVisible = true;
    },
    // async fetchTableData() {
    //   try {
    //     const response = await axios.post(`${baseApi}/manage/searchall`, {}, {
    //       // params: {
    //       //   keyword: this.searchQuery,
    //       // },
    //     });
    //     console.log('运行评估管理模块页面初始化时从后端获取数据', response);

    //     if (response.data.code === 0) {
    //       this.tableData = [];
    //       // 初始化计数器
    //       let index = 1;
    //       response.data.data.forEach((item) => {
    //         const newItem = {
    //           ...item,
    //           index,
    //         };

    //         // 根据 type 字段设置 airLaneType
    //         switch (item.type) {
    //           case 1:
    //             newItem.airLaneType = "起降区";
    //             break;
    //           case 2:
    //             newItem.airLaneType = "航路";
    //             break;
    //           case 3:
    //             newItem.airLaneType = "作业区";
    //             break;
    //           case 4:
    //             newItem.airLaneType = "特殊区域";
    //             break;
    //           case 5:
    //             newItem.airLaneType = "航线";
    //             break;
    //           default:
    //             newItem.airLaneType = "未知类型"; // 如果有其他类型
    //             break;
    //         }

    //         this.tableData.push(newItem);
    //         index++;
    //       });
    //       console.log('从后端获取数据处理后的this.tableData', this.tableData);
    //       this.classifyData()
    //       // this.tableData = response.data.data;
    //     }
    //   } catch (error) {
    //     console.error("获取表格数据失败", error);
    //   }
    // },
    async fetchTableData() {
      try {
        // 原始接口
        const response = await axios.post(`${baseApi}/manage/searchall`, {});

        // 新增两个接口
        const response1 = await axios.post(`${baseApi}/airspace-object/getExtendedEnabledAirspaceObject`, {});
        const response2 = await axios.post(`${baseApi}/airspace-object/getEnabledAirlineArea`, {});

        console.log('运行评估管理模块页面初始化时从后端获取数据', response);
        console.log('从后端获取数据测试新接口1', response1);
        console.log('从后端获取数据测试新接口2', response2);

        // 合并三个接口的有效数据
        const mergedData = [
          ...(response1.data.code === 0 ? response1.data.data : []),
          ...(response2.data.code === 0 ? response2.data.data : []),
        ];

        // 清空旧数据
        this.tableData = [];
        let index = 1;

        // 遍历处理合并后的数据
        mergedData.forEach((item) => {
          const newItem = {
            ...item,
            index,
          };

          switch (item.type) {
            case 1:
              newItem.airLaneType = "起降区";
              break;
            case 2:
              newItem.airLaneType = "航路";
              break;
            case 3:
              newItem.airLaneType = "作业区";
              break;
            case 4:
              newItem.airLaneType = "特殊区域";
              break;
            case 5:
              newItem.airLaneType = "航线";
              break;
            default:
              newItem.airLaneType = "未知类型";
              break;
          }

          this.tableData.push(newItem);
          index++;
        });

        console.log('合并后处理的 this.tableData:', this.tableData);
        this.classifyData();

      } catch (error) {
        console.error("获取表格数据失败", error);
      }
    },
    async classifyData() {
      // 定义四个数组来存储不同类型的数据
      let circularData = []; // 圆柱体数据
      let airLaneData = []; // 航路数据
      let polygonData = []; // 多边形柱体数据
      let secondCircularData = []; // 第二类圆柱体数据

      // 遍历 tableData，根据 type 和 shapes[0].shapeType 分类
      this.tableData.forEach((item) => {
        // 获取第一个 shape 的类型
        const shapeType =
          item.shapes && item.shapes[0] ? item.shapes[0].shapeType : null;

        // 根据 shapeType 添加 mainType、shapeCategory 字段和序号
        if (shapeType === 1) {
          item.shapeCategory = "circular"; // 形状类型
          circularData.push(item); // 圆柱体
        } else if (shapeType === 4) {
          item.shapeCategory = "straight"; // 形状类型
          airLaneData.push(item); // 航路
        } else if (shapeType === 3) {
          item.shapeCategory = "polygonal"; // 形状类型
          polygonData.push(item); // 多边形柱体
        } else if (shapeType === 2) {
          item.shapeCategory = "circular"; // 形状类型（第二类圆柱体）
          secondCircularData.push(item);
        } else {
          console.log("未识别的 shapeType:", shapeType);
        }
      });

      // 输出分类后的结果
      console.log("圆柱体数据:", circularData);
      console.log("航路数据:", airLaneData);
      console.log("多边形柱体数据:", polygonData);
      console.log("第二类圆柱体数据:", secondCircularData);

      // 将这些数据进行处理
      this.handleCircularData(circularData);
      this.handleAirLaneData(airLaneData);
      this.handlePolygonData(polygonData);
      this.handleSecondCircularData(secondCircularData);

      console.log("处理后最后绘制gis的数据", this.gisdata);

      this.classifyAndCalculateArea();
    },
    async classifyAndCalculateArea() {
      // 定义存储各区域面积的变量
      const areaByType = {
        起降区: 0,
        作业区: 0,
        特殊区域: 0,
        航线: 0,
        航路: 0,
        其他区域: 0,
      };

      // 遍历 tableData，按区域计算面积
      for (const item of this.tableData) {
        const airLaneType = item.airLaneType || "其他区域"; // 区域类型
        const shape = item.shapes && item.shapes[0]; // 获取第一个形状

        if (!shape) {
          console.log(`缺少 shape 数据，跳过:`, item);
          continue;
        }

        if (shape.shapeType === 1 || shape.shapeType === 2) {
          // 圆柱体面积计算
          if (shape.rout) {
            const radius = shape.rout;
            const area = Math.PI * Math.pow(radius, 2);
            areaByType[airLaneType] += area;
          } else {
            console.log(`圆柱体缺少 rout 属性，无法计算面积:`, item);
          }
        } else if (shape.shapeType === 3) {
          // 多边形柱体面积计算
          if (shape.points) {
            const positions = shape.points
              .map((point) => [point.longitude, point.latitude])
              .flat();
            console.log("计算多边形面积的position数据", positions);
            try {
              const response =
                await Xmap.AirspaceManage.HierarchicalGrid.AreaCompute(
                  positions
                );
              // const testttt = await Xmap.AirspaceManage.HierarchicalGrid.AreaCompute( [0, 0,   0.0002777777777777778, 0,  0.00027777777777, 0.0002777,  0, 0.0002777  ])
              const area = parseFloat(response);
              areaByType[airLaneType] += area;
            } catch (error) {
              console.error(`多边形面积计算出错: ${error.message}`, item);
            }
          } else {
            console.log(`多边形柱体缺少 points 属性，无法计算面积:`, item);
          }
        } else if (shape.shapeType === 4) {
          // 航路面积计算
          const airLaneData = [item]; // 当前航路数据
          const width = 50; // 航路宽度
          const airLaneArea = this.calculateAirLaneArea(airLaneData, width);
          areaByType[airLaneType] += airLaneArea;
        } else {
          console.log(`未知 shapeType，跳过:`, shape.shapeType);
        }
      }

      // 输出计算结果
      console.log("各区域面积累加结果:", areaByType);
      this.calculateAreaPercentage(areaByType);
      // 返回所有区域面积
      // return areaByType;
    },
    calculateAreaPercentage(areaByType) {
      const totalArea = Object.values(areaByType).reduce(
        (sum, area) => sum + area,
        0
      ); // 总面积

      if (totalArea === 0) {
        console.error("总面积为 0，无法计算占比");
        return;
      }

      const percentageByType = {};

      for (const [type, area] of Object.entries(areaByType)) {
        const percentage = (area / totalArea) * 100;
        percentageByType[type] = {
          area: area.toFixed(2), // 面积保留两位小数
          percentage: percentage.toFixed(2) + "%", // 占比
        };
      }

      console.log("各区域面积占比和面积:", percentageByType);
      console.log("总面积:", totalArea.toFixed(2) + " 平方米");

      return {
        percentageByType,
        totalArea: totalArea.toFixed(2),
      };
    },
    calculateAirLaneArea(item, width) {
      // 地球半径（单位：米）
      const EARTH_RADIUS = 6371000;
      // console.log("我看看要算航路航线面积的数据", item)

      // 计算两点之间的球面距离
      function haversineDistance(lat1, lon1, lat2, lon2) {
        const toRadians = (angle) => (angle * Math.PI) / 180;
        const dLat = toRadians(lat2 - lat1);
        const dLon = toRadians(lon2 - lon1);
        const radLat1 = toRadians(lat1);
        const radLat2 = toRadians(lat2);

        const a =
          Math.sin(dLat / 2) * Math.sin(dLat / 2) +
          Math.cos(radLat1) *
          Math.cos(radLat2) *
          Math.sin(dLon / 2) *
          Math.sin(dLon / 2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return EARTH_RADIUS * c; // 距离单位：米
      }

      // 校验并提取 points
      const shape = item[0].shapes && item[0].shapes[0];
      if (!shape || !shape.points || shape.points.length < 2) {
        console.error(
          "航路数据的 points 不完整，无法计算:",
          shape ? shape.points : null
        );
        return 0;
      }

      const points = shape.points; // 提取 points
      let totalArea = 0;

      for (let i = 0; i < points.length - 1; i++) {
        const point1 = points[i];
        const point2 = points[i + 1];

        // 计算两点之间的距离（单位：米）
        const distance = haversineDistance(
          point1.latitude,
          point1.longitude,
          point2.latitude,
          point2.longitude
        );

        // 计算当前段的面积
        const area = distance * width;
        totalArea += area;

        // console.log(
        //   `航路段子段: [(${point1.latitude}, ${point1.longitude}) -> (${point2.latitude}, ${point2.longitude})]，距离: ${distance.toFixed(
        //     2
        //   )} 米，面积: ${area.toFixed(2)} 平方米`
        // );
      }

      // console.log(`该条航路/航线段总面积: ${totalArea.toFixed(2)} 平方米`);
      return totalArea;
    },
    handleCircularData(data) {
      // 遍历并处理圆柱体数据
      data.forEach((item) => {
        // 只取第一个 shape 进行处理
        const shape = item.shapes[0];
        if (shape) {
          // 根据 item.type 设置颜色
          let color;
          switch (item.type) {
            case 4:
              color = "RED";
              break;
            case 1:
              color = "YELLOW";
              break;
            case 2:
              color = "ORANGE";
              break;
            case 3:
              color = "CYAN";
              break;
            default:
              color = "CYAN"; // 默认颜色
          }

          // 添加字段 'mainType' 和 'sequenceIndex' 到 item
          // item.mainType = 'main1';             // 添加 mainType 字段
          if (item.airLaneType === "起降区") {
            item.mainType = "main_qijiang"; // 对应的值可以根据需要设置
          } else {
            item.mainType = "main1"; // 默认值
          }

          item.sequence = item.index; // 添加 index 字段
          // 处理第一个 shape 的数据，进行绘制等操作
          this.cirularpush(shape, item.index, item.mainType, item.name, color);
        }
      });
    },
    handlePolygonData(data) {
      // console.log("处理数据时的多边体数据", data)
      // 遍历并处理多边形柱体数据
      data.forEach((item) => {
        // 遍历每个 shape，检查 shapeType 是否为 3（多边形柱体）
        item.shapes.forEach((shape) => {
          if (shape.shapeType === 3) {
            // 多边形柱体
            // 从 shape 中获取多边形顶点数据和其他属性
            const points = shape.points; // 获取顶点数据
            const minAltitude = shape.minAltitude; // 获取最小高度
            const maxAltitude = shape.maxAltitude; // 获取最大高度
            const index = item.index; // 获取索引
            const infoid = "main" + item.type; // 根据 type 设置标识符
            const text = item.name; // 获取区域名称
            // 根据 item.type 设置颜色
            let color;
            switch (item.type) {
              case 4:
                color = "RED";
                break;
              case 1:
                color = "YELLOW";
                break;
              case 2:
                color = "ORANGE";
                break;
              case 3:
                color = "CYAN";
                break;
              default:
                color = "CYAN"; // 默认颜色
            }

            // 添加字段 'mainType' 和 'sequenceIndex' 到 item
            item.mainType = "main3"; // 添加 mainType 字段
            item.sequence = item.index; // 添加 index 字段
            // 调用 polygonalpush 函数处理数据
            this.polygonalpush(
              points,
              minAltitude,
              maxAltitude,
              index,
              "main3",
              text,
              color
            );
            // console.log(`多边形柱体 ${item.name} 更新`);
          }
        });
      });
    },
    handleSecondCircularData(data) {
      // 遍历并处理第二类圆柱体数据
      data.forEach((item) => {
        item.shapes.forEach((shape) => {
          if (shape.shapeType === 4) {
            // 第二类圆柱体
            // 添加字段 'mainType' 和 'sequenceIndex' 到 item
            item.mainType = "main4"; // 添加 mainType 字段
            item.sequence = item.index; // 添加 index 字段
            this.cirularpush(shape, item.index, "main4", item.name, "RED");
            // console.log(`第二类圆柱体 ${item.name} 更新`);
          }
        });
      });
    },
    // 切换显示航路或航线
    toggleAirData() {
      this.isShowingHanglu = !this.isShowingHanglu;
      this.drawgis();
      if (!this.isShowingHanglu) {
        console.log("现在是航线，需要建立websocket");
        this.S6drawDrone();
      } else {
        console.log("现在是航路，不需要ws", this.ws);
        if (this.ws) {
          console.log("选择的时刻不需要ws，但是存在了ws，即将清除ws", this.ws);
          this.wsClosing = true; // 标记 WebSocket 正在关闭
          this.ws.onmessage = null; // 禁止处理关闭后的消息
          this.ws.close(); // 关闭 WebSocket 连接
          this.ws = null;
          this.droneModels = [];
        }
      }
    },
    handleAirLaneData(data) {
      // 遍历航路数据并根据 type 使用不同的颜色绘制
      data.forEach((item) => {
        item.shapes.forEach((shape) => {
          // console.log("看看每个航路的info", item.info)
          const isHangxian = item.info !== null; // 判断是否是航路
          let color = "DEEPSKYBLUE"; // 默认颜色为蓝色，用于航线

          if (isHangxian) {
            // 航路颜色设置
            switch (item.info.type) {
              case 0:
                // color = "CHOCOLATE"; // 低速航路
                color = "CORNFLOWERBLUE"; // 高速航路
                break;
              case 1:
                // color = "ORANGE"; // 中速航路
                color = "CORNFLOWERBLUE"; // 高速航路
                break;
              case 2:
                color = "CORNFLOWERBLUE"; // 高速航路
                break;
              case 3:
                color = "DARKCYAN"; // 匝道
                break;
            }
          } else {
            color = "DEEPSKYBLUE"; // 航线的默认颜色为蓝色
          }

          // 检查显示条件
          // if ((isHangxian && this.isShowingHanglu) || (!isHangxian && !this.isShowingHanglu)) {
          if (true) {
            // 添加字段 'mainType' 和 'sequenceIndex' 到 item
            item.mainType = isHangxian ? "main2" : "line"; // 根据类型设置不同的mainType
            item.sequence = item.index; // 添加索引字段

            // 调用绘制航路的方法
            this.straightpush(
              shape.points, // 点数据
              shape.minAltitude, // 底部高度
              shape.maxAltitude, // 顶部高度
              item.index, // 索引
              item.mainType, // 信息 ID
              item.name, // 航路名称
              color // 颜色
            );
          }
        });
      });
    },
    cirularpush(shape, index, infoid, text, color) {
      // 检查 points 数组是否有效
      if (shape.points && shape.points.length > 0) {
        const centerPoint = shape.points[0]; // 获取第一个点作为圆柱体的中心点

        // 确保 centerPoint 有有效的经纬度
        if (centerPoint.latitude && centerPoint.longitude) {
          this.gisdata.circular.push({
            longitude: centerPoint.longitude,
            latitude: centerPoint.latitude,
            minAltitude: shape.minAltitude,
            maxAltitude: shape.maxAltitude,
            radius: shape.rout, // 使用 rout 作为半径
            activeidentityid: infoid,
            index: index,
            color: color,
            text: text,
          });
        } else {
          console.log("Warning: Invalid center point in shape:", shape);
        }
      } else {
        console.log("Warning: No points data for shape:", shape);
      }
    },
    polygonalpush(
      points,
      minAltitude,
      maxAltitude,
      index,
      infoid,
      text,
      color
    ) {
      // 构建多边形数据
      const polygonalData = {
        coordinates: [], // 存放多边形顶点的经纬度和高度
        minAltitude: minAltitude, // 从 shape 获取最小高度
        maxAltitude: maxAltitude, // 从 shape 获取最大高度
        index: index,
        activeidentityid: infoid,
        text: text,
        color: color,
      };

      // 检查 points 是否存在且是一个有效数组
      if (points && Array.isArray(points) && points.length > 0) {
        // 遍历 points 数组中的每个点
        points.forEach((point) => {
          // 确保每个点都包含有效的经纬度和高度
          if (
            point.longitude !== undefined &&
            point.latitude !== undefined &&
            point.altitude !== undefined
          ) {
            // 将点的经纬度和高度存入 coordinates 数组
            polygonalData.coordinates.push({
              longitude: point.longitude,
              latitude: point.latitude,
              altitude: point.altitude, // 添加高度信息
            });
          } else {
            console.log("点数据缺少经纬度或高度信息:", point);
          }
        });
      } else {
        console.log("没有可用的顶点数据 (points 为空或未定义)");
      }

      // 如果有有效的坐标数据，则将多边形数据添加到 GIS 数据结构中
      if (polygonalData.coordinates.length > 0) {
        this.gisdata.polygonal.push(polygonalData);
        console.log("多边形柱体已添加至 GIS 数据:", this.gisdata.polygonal);
      } else {
        console.log("没有有效的多边形坐标数据，未添加到 GIS 数据结构中");
      }
    },

    straightpush(points, minAltitude, maxAltitude, index, infoid, text, color) {
      // console.log('点线形航路数据:', points);

      // 构建 straight 数据结构
      const straightData = {
        coordinates: [], // 包含经纬度和高度的数组
        minAltitude: minAltitude, // 底部高度
        maxAltitude: maxAltitude, // 顶部高度
        index: index,
        activeidentityid: infoid,
        color: color,
        text: text,
      };

      // 遍历 points，提取经纬度和高度信息
      points.forEach((point) => {
        straightData.coordinates.push({
          longitude: point.longitude,
          latitude: point.latitude,
          altitude: point.altitude,
        });
      });

      // 添加到 GIS 数据的 straight 部分
      this.gisdata.straight.push(straightData);
      // console.log('straightData 已添加至 GIS 数据:', straightData);
    },
    // 执行 zoomTo 操作
    zoomToEntities() {
      if (this.viewer.entities.values.length > 0) {
        // this.viewer.zoomTo(this.viewer.entities);
        this.viewer.flyTo(this.viewer.entities, {
          duration: 0, // 飞行动画持续时间，可自行调整
          offset: new Cesium.HeadingPitchRange(
            Cesium.Math.toRadians(150), // 朝向角度
            Cesium.Math.toRadians(-40), // 俯仰角度
            10000 // 距离（可以调整至适合的视距）
          ),
        });
      } else {
        console.log("没有可绘制的实体，跳过 zoomTo 操作");
      }
    },
    async initializeCesium() {
      try {
        this.viewer = new Xmap.Viewer("cesiumContainer").viewer;
        // Xmap.AirspaceManage.HierarchicalGrid.createImageryProvider('xyz',
        //   {
        //     url: 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}'
        //   })
        this.viewer.imageryLayers.addImageryProvider(
          new Cesium.OpenStreetMapImageryProvider({
            // url: `http://192.168.0.135:8001/rsimageofhigh`,
            url: process.env.VUE_APP_MAP,
            fileExtension: "png",
            maximumLevel: 19,
          })
        );
        // // 加载3dtiles模型数据
        // Xmap.AirspaceManage.HierarchicalGrid.load3dtiles('http://192.168.0.135:9027/prod-api/static/3dtiles3/tileset.json')
        Xmap.AirspaceManage.HierarchicalGrid.load3dtiles('http://192.168.0.135:8005/3dtiles/zhuhai3dtile/tileset.json')

        // 全国高程数据
        Xmap.AirspaceManage.HierarchicalGrid.loadDEM(
          process.env.VUE_APP_HEIGHT_MAP,
          true
        );

        // // //开启自动地形遮挡
        // this.viewer.scene.globe.depthTestAgainstTerrain = true;
        // //加载珠海横琴3dtile白模服务
        // var tileset_zhuhai = this.viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
        //   url: 'http://192.168.0.135:8005/3dtiles/zhuhai3dtile/tileset.json'
        // }));

        this.viewer.scene.screenSpaceCameraController.zoomEventTypes = [
          Cesium.CameraEventType.WHEEL,
        ];
        // console.log("Cesium.CameraEventType",Cesium.CameraEventType )
        this.viewer.scene.screenSpaceCameraController.tiltEventTypes = [
          Cesium.CameraEventType.MIDDLE_DRAG, // 鼠标中键按下事件
        ];
        // 设置初始相机视图
        this.viewer.camera.setView({
          destination: Cesium.Cartesian3.fromDegrees(
            113.5405629,
            22.1247559,
            17000
          ),
        });
        console.log("Cesium version", Cesium.VERSION);
      } catch (error) {
        console.error("Cesium initialization failed:", error);
      }
    },
    S6drawDrone() {
      if (this.ws) {
        console.log("Closing previous WebSocket connection");
        this.ws.onmessage = null;
        this.ws.onclose = null;
        this.ws.close();
        this.ws = null;
      }

      this.ws = new WebSocket(`ws://${baseWebsocketApi}/ws/message`);

      this.ws.onopen = () => {
        console.log("ws onopen");
        this.wsClosing = false;
      };

      this.ws.onmessage = (e) => {
        // 检查连接状态和关闭标记
        if (this.wsClosing || this.ws.readyState !== WebSocket.OPEN) {
          console.log("WebSocket is closing or closed, ignoring message.");
          return;
        }
        console.log("ws onmessage");
        console.log("本次websocket传入的数据", e.data);

        const droneData = JSON.parse(e.data);

        // 提取 `devId`、经纬度、和高度信息
        const devId = droneData.devId;
        const latitude = parseFloat(droneData.lat);
        const longitude = parseFloat(droneData.lon);
        const altitude = parseFloat(droneData.height);

        // 查找具有相同 `devId` 的无人机模型
        const existingDrone = this.droneModels.find(
          (model) => model.devId === devId
        );

        // 将位置转换为 `Cartesian3`
        const cartographic = new Cesium.Cartographic(
          Cesium.Math.toRadians(longitude),
          Cesium.Math.toRadians(latitude),
          altitude
        );
        const position =
          Cesium.Ellipsoid.WGS84.cartographicToCartesian(cartographic);

        if (existingDrone) {
          // 如果模型已存在，则更新其位置
          existingDrone.position = position;
        } else {
          // 如果模型不存在，创建并添加无人机模型
          const droneModel = addDroneModel(
            this.viewer,
            position,
            "/drone3.glb"
          );
          droneModel.devId = devId; // 记录 devId 以便下次查找
          this.droneModels.push(droneModel);
        }
        // // 如果模型数组为空，创建模型
        // if (this.droneModels.length === 0) {
        //   droneData.forEach((item) => {
        //     const cartographic = new Cesium.Cartographic(
        //       Cesium.Math.toRadians(item.longitude),
        //       Cesium.Math.toRadians(item.latitude),
        //       item.altitude
        //     );
        //     const position =
        //       Cesium.Ellipsoid.WGS84.cartographicToCartesian(cartographic);

        //     // 创建并添加无人机模型
        //     const droneModel = addDroneModel(
        //       this.viewer,
        //       position,
        //       "/drone3.glb"
        //     );
        //     this.droneModels.push(droneModel);
        //   });
        // } else {
        //   // 更新已存在模型的位置
        //   droneData.forEach((item, index) => {
        //     const cartographic = new Cesium.Cartographic(
        //       Cesium.Math.toRadians(item.longitude),
        //       Cesium.Math.toRadians(item.latitude),
        //       item.altitude
        //     );
        //     const position =
        //       Cesium.Ellipsoid.WGS84.cartographicToCartesian(cartographic);

        //     // 更新模型位置
        //     this.droneModels[index].position = position;
        //   });
        // }
      };

      this.ws.onclose = () => {
        console.log("WebSocket connection closed");
        this.wsClosing = false;
        this.ws = null;
      };
    },
  },

  watch: {
    // 监听 statusDialogVisible 的变化
    statusDialogVisible(newValue, oldValue) {
      if (newValue === false && oldValue === true) {
        // 当 statusDialogVisible 从 1 变为 0 时，调用子组件的 resetSelection 方法
        this.$refs.customTable.resetSelection();
        console.log("resetSelection called");
      }
    },
  },
};
</script>


<style scoped lang="css">
h3 {
  color: #ffffff;
}

/* 顶部内容区样式 */
.header-content {
  position: relative;
  width: 100%;
  /* 使其占据整个宽度 */
  height: 10%;
  background: url("../assets/img/module1/page1top.png") no-repeat;
  background-size: cover;
  display: flex;
  align-items: center;
  /* 垂直居中 */
  padding: 5px;
  /* 增加内部间距 */
}

/* 标题样式 */
.header-title {
  background-image: linear-gradient(180deg,
      rgba(200, 215, 228, 1) 0,
      rgba(255, 255, 255, 1) 100%);
  position: relative;
  flex: 2;
  margin-left: 5%;
  width: 20%;
  color: rgba(112, 112, 112, 1);
  font-size: 20px;
  font-weight: 600;
  letter-spacing: 1px;
  font-family: PangMenZhengDao-3;
  text-align: left;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 图标样式 */
.header-icon {
  position: relative;
  width: 22px;
  height: 20px;
  margin-left: 20px;
  /* 与其他内容间隔 */
  margin-top: -20px;
}

.image_3 {
  position: absolute;
  /* 图片绝对定位，不影响布局 */
  top: 14%;
  left: 15%;
  width: 80%;
  /* 让图片宽度覆盖整个容器 */
  height: 80%;
  /* 让图片高度覆盖整个容器 */
  z-index: 0;
  /* 将背景图片置于内容下层 */
}

.right-panel-container {
  position: absolute;
  width: 34% !important;
  height: 76%;
  color: white;
  padding: 20px;
  z-index: 5;
}

.img_left_title {
  position: relative;
  left: 0%;
  top: 5%;
  background-size: 100% 100%;
  /* background-color: rgba(200, 215, 228, 1); */
}

.text_left_title {
  position: absolute;
  left: 19%;
  top: 5.9%;
  width: 60%;
  font-family: "smallTitleFont", sans-serif;
  overflow-wrap: break-word;

  background-image: linear-gradient(180deg,
      rgba(200, 215, 228, 1) 0,
      rgba(255, 255, 255, 1) 100%);
  color: rgba(112, 112, 112, 1);
  font-size: 20px;
  letter-spacing: 1px;
  /* font-family: PangMenZhengDao-3; */
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 23px;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.left-panel-container {
  position: absolute;
  width: 22% !important;
  border-radius: 4px;
  pointer-events: auto;
  /* 确保容器可交互 */
  box-shadow: none;
  /* 添加投影增强可视性 */
  position: absolute;
  top: 5%;
  left: 0%;
  height: 70%;
  color: white;
  padding: 20px;
  z-index: 5;
  pointer-events: auto;
}


.cesiumContainerBox {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  pointer-events: none;
  /* 允许穿透 */

  #cesiumContainer {
    pointer-events: auto;
    /* 保留地图基础交互 */
  }

  .layer {
    pointer-events: none;
    /* 禁用覆盖层拦截 */
  }
}

.panel-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-top: 20px;
  margin-left: 2%;
  z-index: 4;
  width: 390px;
}

.chart-container {
  display: flex;
  justify-content: space-between;
  gap: 10px;
  /* 增加图表间距 */
  width: 100%px;
}

.chart-item {
  flex: 1;
  /* 弹性填充 */
  height: 150px;
  /* 适当降低高度 */
  background: rgba(0, 24, 47, 0.5);
  border: 1px solid #03498f;
  border-radius: 4px;
  margin-top: 20px;
  width: 48%;
}

.alert-table-container {
  flex: 1;
  max-height: 550px;
  /* 控制表格最大高度 */
  overflow-y: auto;
  /* 允许滚动 */
  width: 100%;
  background-color: #0d263b4d;
  /* ✅ 隐藏滚动条（兼容 Chrome / Edge） */
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE/Edge */
  /* ✅ 隐藏滚动条（兼容 WebKit） */
}

.alert-table-container::-webkit-scrollbar {
  display: none;
  /* Chrome/Safari/Edge 隐藏滚动条 */
}

/* 表格自适应宽度 */
.alert-table-container>>>.el-table {
  width: 100% !important;
}

/* 强制表格头部宽度为 100% */
.alert-table-container /deep/ .el-table__header {
  width: 100% !important;
}

/* 调整按钮位置 */
.table-button-display,
.table-button-hidden {
  top: 10px;
  right: 10px;
}

/* 调整饼图标题位置 */
.echarts-title {
  padding-top: 10px !important;
}

/* 调整图例位置 */
.echarts-legend {
  top: 40px !important;
}

.table-actions {
  position: relative;
  width: 100%;
  margin-top: 20px;
  /* 增加与饼图的间距 */
  z-index: 1;
}

/* 调整表格容器 */
.table-context {
  max-height: 400px;
  overflow-y: auto;
  margin-top: 20px;
  width: 100%;
}

/* 滚动条样式 */
.table-context::-webkit-scrollbar {
  width: 6px;
  background: rgba(0, 24, 47, 0.8);
}

.table-context::-webkit-scrollbar-thumb {
  background: #03498f;
  border-radius: 4px;
}

.cesiumContainerBox {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

#cesiumContainer {
  width: 100%;
  height: 100%;
}

.table-actions {
  position: relative;
  /* background-color: #ffffff; */
  /* left: 5%;
  top: 10%; */
  z-index: 1;
  width: 300px;
  height: 30px;
}

.table-actions-2 {
  position: absolute;
  left: 30%;
  top: 9%;
  z-index: 1;
  width: 100%;
  height: 7%;
  pointer-events: auto;
}

.search-input {
  position: relative;
  left: 0%;
  top: 6%;
  height: 100%;
  width: auto;
  z-index: 1;
  border: none;
  background-image: url("../assets/img/module2/search.png");
  background-size: contain;
  /* 背景图片覆盖按钮大小 */
  background-color: transparent;
  background-size: 100% 100%;
  /* 背景图片覆盖按钮大小 */
  /* color: #ffffff; */
  padding-left: 10px;
  /* 添加内边距 */
  font-family: AlibabaPuHuiTi_2_55_Regular;
  font-weight: NaN;
  color: white;
}

.search-input option {
  /* background-color: #000000; 背景颜色 */
  color: black;
  /* 文字颜色 */
  font-family: AlibabaPuHuiTi_2_55_Regular;
  font-weight: normal;
  padding: 5px;
  /* 内边距 */
}

.search-input::placeholder {
  font-family: AlibabaPuHuiTi_2_55_Regular;
  color: #ffffff;
  font-weight: NaN;
  font-size: 14px;
  padding-left: 6px;
  /* 添加内边距 */
}

.filter-button {
  background-image: url("../assets/img/module2/filtericon1.png");
  position: absolute;
  background-size: contain;
  /* 背景图片覆盖按钮大小 */
  background-repeat: no-repeat;
  background-color: transparent;
  color: transparent;
  left: 18%;
  top: 24%;
  width: 15px;
  height: 15px;
  z-index: 3;
  border: none;
  cursor: pointer;
  filter: brightness(0.1);
}

.filer-button:active {
  opacity: 0.8;
  /* 点击时使按钮变暗 */
}

.sort-select {
  position: absolute;
  left: 22%;
  top: 6%;
  width: 18%;
  height: 60%;
  z-index: 1;
  background-image: url("../assets/img/module2/search.png");
  background-size: 100% 100%;
  /* 背景图片覆盖按钮大小 */
  background-repeat: no-repeat;
  background-color: transparent;
  border: none;
  /* 去除边框 */
  border-radius: 4px;
  /* 设置圆角 */
  color: #ffffff;
  /* 设置文字颜色 */
  padding-left: 10px;
  /* 设置左侧内边距 */
  font-size: 14px;
  font-family: AlibabaPuHuiTi_2_55_Regular;
  font-weight: NaN;
}

.sort-button {
  background-image: url("../assets/img/module2/sorticon1.png");
  position: absolute;
  background-size: contain;
  /* 背景图片覆盖按钮大小 */
  background-repeat: no-repeat;
  background-color: transparent;
  color: transparent;
  left: 40%;
  top: 11%;
  width: 5%;
  height: 60%;
  z-index: 3;
  border: none;
  cursor: pointer;
}

.table-container2 {
  position: absolute;
  left: 50%;
  top: 6%;
  width: 30%;
  height: 80%;
  z-index: 1;
  display: block;
}

.table-context {
  position: absolute;
  /* background-color: rgb(0, 247, 255); */
  left: 5%;
  top: 13.5%;
  z-index: 1;
  width: 60%;
  height: 70%;
}

/* 旧元素 */
.plan-diolog {
  z-index: 1;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
  height: 80%;
  /* 设置高度，使布局固定 */
}

.plan-diolog-left-pane {
  width: 45%;
  /* 左侧占 50% 宽度 */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.plan-diolog-left-up-pane {
  padding: 10px;
  border-radius: 5px;
  margin-bottom: 20px;
}

.plan-diolog-left-down-pane {
  padding: 10px;
  border-radius: 5px;
}

.plan-diolog-right-pane {
  width: 55%;
  /* 右侧占 35% 宽度 */
  display: flex;
  flex-direction: column;
  align-items: center;
}

h1 {
  color: #ffffff;
}

h2 {
  color: #ffffff;
}

h3 {
  color: #ffffff;
}

.table-button-display {
  background-image: url("../assets/img/module1/button-tijiao.png");
  position: absolute;
  background-size: 100% 100%;
  /* 背景图片覆盖按钮大小 */
  background-color: transparent;
  color: transparent;
  right: 0%;
  /* left: 46%; */
  /* top: 5%; */
  height: 30px;
  width: 50px;
  border: none;
  cursor: pointer;
  color: white;
  font-size: 16px;
  text-align: center;
  line-height: 8px;
  z-index: 2;
}

.table-button-hidden {
  background-image: url("../assets/img/module1/button-bohui.png");
  position: absolute;
  background-size: 100% 100%;
  /* 背景图片覆盖按钮大小 */
  background-color: transparent;
  color: transparent;
  right: 0%;
  /* left: 46%; */
  /* top: 5%; */
  height: 30px;
  width: 50px;
  border: none;
  cursor: pointer;
  color: white;
  font-size: 16px;
  text-align: center;
  line-height: 8px;
  z-index: 2;
}

.expand-content {
  padding: 10px;
  background-color: transparent;
  border: none;
}

.detail-row {
  display: grid;
  grid-template-columns: 80px 1fr 80px 1fr;
  gap: 10px;
  margin-bottom: 8px;
  align-items: center;
}

.detail-label {
  color: #87b7da;
  font-size: 12px;
}

.action-buttons {
  margin-top: 12px;
  text-align: center;
}

/* 状态颜色 */
.status-processing {
  color: #e6a23c;
}

.status-resolved {
  color: #67c23a;
}

.status-pending {
  color: #f56c6c;
}

/* 风险等级标识 */
.alert-level-4 {
  color: #e6a23c;
}

.alert-level-5 {
  color: #f56c6c;
}

/* 表格样式 */
.alert-table {
  background: transparent;
  color: #fff;
}

.alert-table::v-deep .el-table__header th {
  background: #00284d;
  color: #87b7da;
}

.alert-table::v-deep .el-table__row {
  background: rgba(0, 24, 47, 0.8);
  color: #fff;
}

.alert-table::v-deep .el-table__row:hover {
  background: rgba(0, 40, 77, 0.8);
}

.alert-table-container /deep/ .el-table .el-table__body tr:hover {
  background-image: none !important;
  font-weight: normal !important;
}

/* 滚动条样式 */
.alert-table-container /deep/ .el-table__body-wrapper::-webkit-scrollbar {
  width: 8px;
  background: rgba(0, 24, 47, 0.8);
}

.alert-table-container /deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background: #004098;
  border-radius: 4px;
}

.alert-table-container /deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
  background: #004098;
}

/* 最外层透明表格背景与白色字体 */
.alert-table-container /deep/ .el-table,
.alert-table-container /deep/ .el-table__expanded-cell {
  background-color: transparent;
  color: white;
  padding: 0;
}

/* 设置表格边框 */
.alert-table-container /deep/ .el-table__body-wrapper {
  border: none;
}

/* 数据行 */
.alert-table-container /deep/ .el-table__expand-icon {
  height: 34px;
  color: #ffffff;
}

/* 确保所有内部元素没有边框 */
.alert-table-container /deep/ .el-table .el-table__body-wrapper .el-table__row,
.alert-table-container /deep/ .el-table .el-table__body-wrapper .el-table__header th,
.alert-table-container /deep/ .el-table .el-table__body-wrapper .el-table__body tr td {
  border: none !important;
}

.alert-table-container /deep/ .el-table::before {
  height: 0px;
}

/* 按钮样式 */
.report-btn {
  background-color: transparent;
  border: 1px solid #409eff;
  color: #409eff;
}

/* 悬停时的样式 */
.report-btn:hover {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.control-btn {
  background-color: transparent;
  border: 1px solid #409eff;
  color: #409eff;
}

.control-btn:hover {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.control-btn:active {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.history-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #f0f2f5;
  z-index: 1000;
  overflow: auto;
}

.content-info {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-image: url("~@/assets/demo/assets/images/basicInfo/map.png");
  background-position: 100%;
  background-repeat: no-repeat;
  background-size: 100% 100%;


  .content-info-container {
    width: 100%;
    height: 100%;
    background-image: url("~@/assets/demo/assets/images/basicInfo/bg.png");
    background-position: 100%;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    padding: 0 60px;
  }
}

.next-page-btn {
  padding: 8px 20px;
  font-size: 14px;
}

.cesiumContainerBox {
  width: 100%;
  position: relative;
  height: 83vh;
  margin: 0;
  padding: 0;

  .mapBg {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 3;
    pointer-events: none;
  }

  .layer {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 2;
    pointer-events: none;
    box-shadow: inset -200px 0px 60px -20px rgb(6 7 29 / 35%),
      inset 200px 0px 60px -20px rgb(6 7 29 / 35%);
  }
}

.switch-btn {
  padding: 5px 20px;
  border: none;
  cursor: pointer;
  background: url('~@/assets/img/combined/button_choice_unselected.png') no-repeat;
  /* 未选中状态的背景图 */
  background-size: 100% 100%;
  color: #fff;
  /* 按钮文字颜色 */
  transition: all 0.3s ease;
  pointer-events: auto;
  float: right;
  margin-top: 2px;
  width: 100%;
}


/* 告警表格行高亮颜色样式 */
.alert-table-container>>>.warning-row {
  background-color: rgba(255, 165, 0, 0.1) !important;
}

.alert-table-container>>>.danger-row {
  background-color: rgba(255, 99, 71, 0.15) !important;
}

/* 强化 hover */
.alert-table-container>>>tr.warning-row:hover>td {
  background-color: rgba(255, 165, 0, 0.25) !important;
}

.alert-table-container>>>tr.danger-row:hover>td {
  background-color: rgba(255, 99, 71, 0.3) !important;
}

/* 展开区域背景也跟着主行变色 */
.alert-table-container>>>.el-table__expanded-cell {
  background-color: rgba(255, 255, 255, 0.05);
}

.alert-table-container>>>tr.warning-row+tr.el-table__expanded-row .el-table__expanded-cell {
  background-color: rgba(255, 165, 0, 0.1) !important;
}

.alert-table-container>>>tr.danger-row+tr.el-table__expanded-row .el-table__expanded-cell {
  background-color: rgba(255, 99, 71, 0.15) !important;
}

/* 展开内容根据等级变色 */
.alert-table-container>>>.warning-expand {
  background-color: rgba(255, 165, 0, 0.1) !important;
}

.alert-table-container>>>.danger-expand {
  background-color: rgba(255, 99, 71, 0.15) !important;
}

/* 可选：按钮区域也可以跟着走浅色背景 */
.alert-table-container>>>.warning-expand .action-buttons {
  background-color: transparent;
}

.alert-table-container>>>.danger-expand .action-buttons {
  background-color: transparent;
}
</style>
<style scoped lang="css" src="../assets/indexModule6.css" />
